/**
 * CS307 Team 11 Spring 2011
 * @author Kevin Barlow
 * @author David Barnes
 * @author Max Cohen
 * @author Yoongu Kang
 * @author Matt Lathrop
 * @author Thomas Maley
 *
 *	This class is responsible for sending emails and sms to a list of people
 *	
 */

package com.cs307.redcross.server;

import java.util.Properties;

import java.util.Vector;

import javax.mail.Folder;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.NoSuchProviderException;
import javax.mail.Session;
import javax.mail.Store;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import com.cs307.redcross.client.*;

import com.cs307.redcross.client.Person;

public class Mail{
	static String userName = "msgspammer@gmail.com";
	static String passWord = "spamer12";

	//needs to take a reminder instead of a Vector<Person> is what I believe
	//kind of makes sense due to ability for the client not being able to import client side packages
	//think of this the next time your programming because this is something new for you
	//make your mistakes early because you will be a CEO of a company one day
	public static boolean sendSMS(  Vector<Person> to, String message, String subject){
		//System.out.println("sending sms server " + to + message + subject);
		//TODO: Test limits for this
		//limit may be 100 0-99 will have to work around this
		
		String host = "smtp.gmail.com";
		String port = "465";
		String starttls = "true";
		String auth = "true";
		boolean debug = false;
		String socketFactoryClass = "javax.net.ssl.SSLSocketFactory";
		String fallback = "false";
		String from = "heloasdf";
		//String subject = "subject";
		
		
		
		Properties props = new Properties();
        props.put("mail.smtp.user", userName);
        props.put("mail.smtp.host", host);
		
		if(!"".equals(port))
			props.put("mail.smtp.port", port);
		
		if(!"".equals(starttls))
			props.put("mail.smtp.starttls.enable",starttls);
        
		props.put("mail.smtp.auth", auth);
		
		props.put("mail.smtp.debug", "false");         
		
		if(!"".equals(port))
			props.put("mail.smtp.socketFactory.port", port);
		
		if(!"".equals(socketFactoryClass))
			props.put("mail.smtp.socketFactory.class",socketFactoryClass);
		
		if(!"".equals(fallback))
			props.put("mail.smtp.socketFactory.fallback", fallback);
		
        try
        {
			Session session = Session.getDefaultInstance(props, null);
            session.setDebug(debug);
            MimeMessage msg = new MimeMessage(session);
            msg.setText( message );
            msg.setSubject(subject);
            msg.setFrom(new InternetAddress( from ));
			int i=0;
            for ( Person p : to ){
				i++;
				if ( i%99 ==0 )
					Thread.sleep(15000);
				if(p!=null)		
					msg.addRecipient(Message.RecipientType.BCC, new InternetAddress( p.getSmsEmail() ) );	//sends sms
			}
            msg.saveChanges();
			Transport transport = session.getTransport("smtp");
			//System.out.println("transport: " + transport);
			transport.connect(host, userName, passWord);
			transport.sendMessage(msg, msg.getAllRecipients());
			transport.close();
			return true;
        }
        catch (Exception mex)
        {
            mex.printStackTrace();
			return false;
        }
	}
	
	public static boolean sendeMail( Vector<Person> to, String message, String subject){
		//TODO: Test limits for this
		//limit may be 100 0-99 will have to work around this
		
		
		String host = "smtp.gmail.com";
		String port = "465";
		String starttls = "true";
		String auth = "true";
		boolean debug = false;
		String socketFactoryClass = "javax.net.ssl.SSLSocketFactory";
		String fallback = "false";
		String from = "heloasdf";
		//String subject = "subject";
		
		
		
		Properties props = new Properties();
        props.put("mail.smtp.user", userName);
        props.put("mail.smtp.host", host);
		
		if(!"".equals(port))
			props.put("mail.smtp.port", port);
		
		if(!"".equals(starttls))
			props.put("mail.smtp.starttls.enable",starttls);
        
		props.put("mail.smtp.auth", auth);
		
		props.put("mail.smtp.debug", "false");         
		
		if(!"".equals(port))
			props.put("mail.smtp.socketFactory.port", port);
		
		if(!"".equals(socketFactoryClass))
			props.put("mail.smtp.socketFactory.class",socketFactoryClass);
		
		if(!"".equals(fallback))
			props.put("mail.smtp.socketFactory.fallback", fallback);
		
        try
        {
			Session session = Session.getDefaultInstance(props, null);
            session.setDebug(debug);
            MimeMessage msg = new MimeMessage(session);
            msg.setText( message );
            msg.setSubject(subject);
            msg.setFrom(new InternetAddress( from ));
            int i=0;
			for ( Person p : to ){
				i++;
				if ( i % 99 == 0 ){
					Thread.sleep(15000);
				}
				msg.addRecipient(Message.RecipientType.BCC, new InternetAddress( p.getEmail() ) );	//sends sms
			}
            msg.saveChanges();
			Transport transport = session.getTransport("smtp");
			transport.connect(host, userName, passWord);
			transport.sendMessage(msg, msg.getAllRecipients());
			transport.close();
			return true;
        }
        catch (Exception mex)
        {
            mex.printStackTrace();
			return false;
        }
	}
	public static boolean sendSMS( Reminder r ){
		Vector<Person> people = r.getPeople();
		for(Group g : r.getGroups())
		{
			if(g!=null)
			{
				for(Person p: g.getPersonList())
				{
					if(p!=null && !people.contains(p))
						people.add(p);
				}
			}
		}
		String message = r.getMessage();
		String subject = r.getEvent().getName();
		
		boolean sms = sendSMS( people, message, subject );
		
		return sms;
	}
 
	public static boolean sendEmail( Reminder r){
		
		Vector<Person> people = r.getPeople();
		String message = r.getMessage();
		String subject = r.getEvent().getName();
		for(Group g : r.getGroups())
		{
			if(g!=null)
			{
				for(Person p: g.getPersonList())
				{
					if(p!=null && !people.contains(p))
						people.add(p);
				}
			}
		}
		boolean email = sendeMail( people, message, subject );
		return email;
	}
	public static boolean sendMessage( Reminder r ){
		
		Vector<Person> people = r.getPeople();
		String message = r.getMessage();
		String subject = r.getEvent().getName();
		for(Group g : r.getGroups())
		{
			if(g!=null)
			{
				for(Person p: g.getPersonList())
				{
					if(p!=null && !people.contains(p))
						people.add(p);
				}
			}
		}
		boolean sms = true;
		boolean email = true;
		
		if(r.isSMS()) sms = sendSMS( people, message, subject );
		if(r.isEmail()) email = sendeMail( people, message, subject );
		
		return sms && email;
	}
	public static boolean getMail(){
		
		Properties props = System.getProperties();
		props.setProperty("mail.store.protocol", "imaps");
		props.setProperty("mail.imap.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
		props.setProperty("mail.imap.socketFactory.fallback", "false");
		
		try {
			
			Session session = Session.getDefaultInstance(props, null);
			Store store = session.getStore("imaps");
			store.connect("imap.gmail.com", userName, passWord );
			Folder folder = store.getFolder("INBOX");
			folder.open(Folder.READ_ONLY);
			
			//BufferedReader reader = new BufferedReader(new InputStreamReader(System.in));
			
			// Get directory
			Message message[] = folder.getMessages();
			
			for ( Message m : message ){
				System.out.println( m.getFrom()[0] );
				System.out.println( m.getSubject() );
				System.out.println( m.getContent() );
			}
			
			// Close connection
			folder.close(false);
			store.close();
		} catch (NoSuchProviderException e) {
			e.printStackTrace();
			//System.exit(1);
			return false;
		} catch (MessagingException e) {
			e.printStackTrace();
			return false;
			//System.exit(2);
		}catch (Exception e) {
			
		}

		return true;
	}

}